use super::{ground::Ground, Client, RNull, VBase, VMap, VRece, VSend};
use std::time::Duration;
use tokio::time::sleep;
use tracing::{instrument, warn};

#[instrument(skip_all, name = "time_job")]
pub async fn time_job(tx: VSend, client: &Client) {
    let gd = Ground;

    loop {
        if let Err(e) = gd.load_db("1", client, &tx).await {
            warn!("time job error: {:?}", e);
        }

        // 3 minutes
        sleep(Duration::from_secs(60 * 3)).await;
    }
}

#[instrument(skip_all, name = "queue_job")]
pub async fn queue_job(rx: &VRece, client: &Client) {
    loop {
        if let Err(e) = do_buffer(rx, client).await {
            warn!("queue error: {:?}", e);
        }
    }
}

#[instrument(skip_all, name = "buffer")]
async fn do_buffer(rx: &VRece, client: &Client) -> RNull {
    if let Ok(d) = rx.recv().await {
        warn!("buf len: {:?}", rx.len());

        let data = d.ckobj()?;

        let cmd = match data.k_str("cmd") {
            Some(v) => v,
            None => "",
        };

        let gd = Ground;

        match cmd {
            "update" => {
                gd.update(data, client).await?;
            }
            "upval" => {
                gd.update_val(data, client).await?;
            }
            _ => {
                warn!("buffer, no cmd");
            }
        }
    }

    Ok(())
}
